import $request from '@/utils/request.js';

export default {
	// 校验登录态
	onVerifyLogin() {
		let status = false;
		const token = uni.getStorageSync('token');
		if (token) {
			status = true;
		}
		return status;
	},
	// 更新登录态
	onUpdateLoginStatus() {
		return new Promise((resolve, reject) => {
			const loginStatus = this.onVerifyLogin();
			resolve({
				isLogin: loginStatus,
				userId: uni.getStorageSync('userId'),
				nickName: uni.getStorageSync('nickName'),
				avatar: uni.getStorageSync('avatar'),
				mobile: uni.getStorageSync('mobile')
			})
		})
	},
	// 登录态拦截 
	onLoginIntercept() {
		const isLogin = this.onVerifyLogin();
		return new Promise((resolve, reject) => {
			if (isLogin) {
				resolve();
			} else {
				reject();
				uni.showToast({
					icon: 'error',
					title: '请登陆后使用该功能',
					mask: true,
					duration: 2000
				})
			}
		})
	},
	// 获取定位
	onFetchLocation() {
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'wgs84',
				altitude: true,
				success: (res) => {
					$request({
						url: '/blade-client-business/app/convert/locations',
						data: {
							locations: `${res.longitude},${res.latitude}`
						}
					}).then(result => {
						const address = JSON.parse(result.data);
						const {
							regeocode
						} = address;
						const {
							addressComponent = {},
								formatted_address
						} = regeocode;
						const {
							adcode,
							province,
							city,
							district,
							streetNumber = {}
						} = addressComponent;
						let addressList;
						let coordinate = streetNumber.location.split(',');
						if (formatted_address.indexOf(`${streetNumber.number}`) > 0) {
							addressList = formatted_address.split(`${streetNumber.number}`);
						} else {
							addressList = formatted_address.split(
								`${addressComponent.township}`);
						}
						resolve({
							adcode,
							province,
							city,
							district,
							address: addressList[1],
							longitude: coordinate[0],
							latitude: coordinate[1]
						})
					})
				},
				fail: (error) => {
					reject(error)
				}
			})
		})
	},
	// 选择定位
	onSelectLocation() {
		return new Promise((resolve, reject) => {
			uni.chooseLocation({
				success: (res) => {
					$request({
						url: '/blade-client-business/app/convert/locations',
						data: {
							locations: `${res.longitude},${res.latitude}`
						}
					}).then(result => {
						const address = JSON.parse(result.data);
						const {
							regeocode
						} = address;
						const {
							addressComponent = {}
						} = regeocode;
						const {
							streetNumber = {}
						} = addressComponent;
						let coordinate = streetNumber.location.split(',');
						resolve({
							address: res.name,
							longitude: coordinate[0],
							latitude: coordinate[1]
						})
					})
				},
				fail: (error) => {
					reject(error)
				}
			});
		})
	},
	// 上传文件
	onUploadFile(path) {
		let baseUrl = 'https://www.gxjuxinxiang.com/api';//https://sport.dbs12580.com:441/api   https://www.gxjuxinxiang.com/api
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${baseUrl}/blade-resource/oss/endpoint/put-file`,
				filePath: path,
				name: 'file',
				success: (res) => {
					resolve(JSON.parse(res.data))
				},
				fail: (error) => {
					reject('上传失败')
				}
			});
		})
	},
	// 支付
	onPayment(params, id) {
		uni.showLoading({
			title: '支付中',
			mask: true
		})
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				...params,
				signType: 'RSA',
				success: res => {
					this.onFetchPaymentResult(id, resolve, reject);
				},
				fail: error => {
					uni.showToast({
						icon: 'error',
						title: '支付失败',
						mask: true,
						duration: 2000
					})
					reject(error);
				}
			})
		})
	},
	// 查询支付结果
	onFetchPaymentResult(id, resolve, reject) {
		$request({
			url: '/blade-client-business/app/order/other-order-status',
			data: {
				orderPaymentId: id
			}
		}).then(res => {
			if (res?.code === 200) {
				if (res?.data === 'S') {
					uni.showToast({
						icon: 'success',
						title: '支付成功',
						mask: true,
						duration: 2000
					})
					resolve();
				} else if (res?.data === 'A') {
					this.onFetchPaymentResult(id, resolve, reject);
				} else {
					reject();
					uni.showToast({
						icon: 'error',
						title: '支付异常',
						mask: true,
						duration: 2000
					})
				}
			}
		})
	},
	// 退出登录
	onLogout() {
		uni.removeStorageSync('token');
		uni.removeStorageSync('avatar');
		uni.removeStorageSync('nickName');
		uni.removeStorageSync('tokenType');
		uni.removeStorageSync('userId');
		uni.removeStorageSync('identity');
		
		uni.reLaunch({
			url:"/pages/login/login"
		})
	},
	//获取以后7天的日期包含当天
	getLast7DaysDates() {
	  let dates = [];
	  let daysOfWeek = [];
	  let today = new Date();
	 
	  for (let i = 0; i < 7; i++) {
	    let date = new Date(today);
	    date.setDate(today.getDate() + i); // 设置为今天之前的日期
	    let dayOfWeek = date.getDay(); // 获取星期几 (0-6, 0是周日)
	 
	    dates.push(date.toISOString().split('T')[0]); // 将日期转换为YYYY-MM-DD格式
	    daysOfWeek.push(dayOfWeek); // 将星期几添加到数组中
	  }
	 
	  return {
	    dates: dates, // 将数组逆序，使其从今天开始
	    daysOfWeek: daysOfWeek // 同样逆序星期数组
	  };
	},
	//首页头部三个数据日期:0今日，1近七天，2本月数据，
	homeTabsDate(value){
		var today = new Date();
		var startDate = '';
		var endDate = '';
		
		if(value == 0){
			//今日
			startDate = today.toISOString().split('T')[0]+' 00:00:00';
			endDate = today.toISOString().split('T')[0]+' 23:59:59';
		} else if (value == 1){
			//近七天
			let date = new Date(today);
			date.setDate(today.getDate() - 6);
			startDate = date.toISOString().split('T')[0]+' 00:00:00';
			endDate = today.toISOString().split('T')[0]+' 23:59:59';
		} else if (value == 2){
			//本月
			var fullYear = today.getFullYear();
			var month = today.getMonth()+1;
			var monthLastDay = new Date(fullYear, month, 0);
			startDate = fullYear+'-'+(month<10?'0'+month:month)+'-01';
			endDate = monthLastDay.toISOString().split('T')[0]+' 23:59:59'
		}
		return {
			startDate: startDate,
			endDate: endDate
		};
	},
	//根据年月日计算至今为止的年份
	calculateAge(birthDateString){
		// 将生日字符串转换为Date对象
	  var birthDate = new Date(birthDateString);
	  // 获取当前日期
	  var currentDate = new Date();
	  // 计算年份差值
	  var age = currentDate.getFullYear() - birthDate.getFullYear();
	  // 如果当前日期还没到生日那一年，则年龄减1
	  if (currentDate.getMonth() < birthDate.getMonth() || 
		  (currentDate.getMonth() == birthDate.getMonth() && currentDate.getDate() < birthDate.getDate())) {
		age--;
	  }
	  return age;
	}
}
